package com.vagavaga.bizworld.jpatx;

import java.util.HashMap;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import org.apache.log4j.Logger;

import com.vagavaga.bizworld.SessionProducer;

public class JPATX {
    private static final Logger log = Logger.getLogger(JPATX.class);

    private static HashMap<String, EntityManagerFactory> config = new HashMap<String, EntityManagerFactory>();

    public static EntityManager createEntityManager(SessionProducer producer) {
        synchronized (config) {
            if (!config.containsKey(producer.getPersistenceUnitName())) {
                config.put(producer.getPersistenceUnitName(), Persistence.createEntityManagerFactory(
                        producer.getPersistenceUnitName(),
                        producer.getConfiguration()));
            }
            return config.get(producer.getPersistenceUnitName()).createEntityManager();
        }
    }

    public static EntityManager entityManager(SessionProducer producer) {
        EntityManager em = TxManager.currentEntityManager(producer.getPersistenceUnitName());
        if (em == null) {
            em = createEntityManager(producer);
            TxManager.bind(producer.getPersistenceUnitName(), em);
            return ParentEntityManager.wrap(em, producer.getPersistenceUnitName());
        }
        return ChildEntityManager.wrap(em, producer.getPersistenceUnitName());
    }

    public static void close(EntityManager em) {
        if (em == null) return;
        try {
            em.close();
        } catch (RuntimeException e) {
            log.error("Unable to close EntityManager", e);
        }
    }

    public static void rollback(EntityTransaction tx) {
        try {
            tx.rollback();
        } catch (RuntimeException e) {
            log.error("Unable to rollback EntityTransaction", e); 
        }
    }
}
